package com.yonyou.crm.sprc.oppflow.ctrl;

import com.yonyou.crm.base.doc.rmitf.IBaseDocRmService;
import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.common.rest.constant.HttpKeyConstant;
import com.yonyou.crm.common.rest.constant.PCCodeConstant;
import com.yonyou.crm.common.rest.util.RequestUtil;
import com.yonyou.crm.common.rest.util.ResponseUtil;
import com.yonyou.crm.sprc.oppflow.entity.OppflowVO;
import com.yonyou.crm.sprc.oppflow.rmitf.IOppflowRmService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RestController
@RequestMapping(value = "/sprc/oppflows")
public class OppflowCtrl {

	@Autowired
	private IOppflowRmService service;

	@Autowired
	private IBaseDocRmService baseDocRmService;
	/**
	 * 根据ID数组返回档案信息和档案详情
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "docs", method = RequestMethod.GET)
	public Object getDocAndDetailList(HttpServletRequest request, HttpServletResponse response)
			throws CrmMessageException {

		Map<String,Object> map = new HashMap<String,Object>();
		map.put("11","flowState");
		Map baseDocList = baseDocRmService.getDocAndDetailList(map);
		JSONObject result = new JSONObject();
		result.put("enumData", baseDocList);
		return ResponseUtil.getObject(result);
	}


	/**
	 * 商机动作列表
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(method = RequestMethod.GET)
	public Object list(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		JSONObject paramObj = RequestUtil.getParamObject(request);

		JSONObject data = new JSONObject();
		@SuppressWarnings("unchecked")
		List<OppflowVO> flowList = service.getList((Map<String, Object>)paramObj.get("searchMap"));
		data.put("data", flowList);

		return ResponseUtil.getObject(data);

	}

	/**
	 * 新增商机动作
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST)
	public Object insert(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		JSONObject paramObject = RequestUtil.getParamObject(request);
		JSONObject flowData = paramObject.getJSONObject("flowData");//流程数据
		String biztype = flowData.getString("biztype");
		int flag = service.checkBiztypeRepeat(biztype);
		if(flag>0){
			throw new CrmMessageException(PCCodeConstant.ServerError, "当前业务类型已包含商机流程");
		}
		OppflowVO vo = RequestUtil.getVO(flowData, OppflowVO.class);

		Map<String, List<Map<String, Object>>> ctrlInsertData = ctrlInsertData(paramObject);
		List<Map<String, Object>> flowStageList = ctrlInsertData.get("flowStageList");
		List<Map<String, Object>> stageActionList = ctrlInsertData.get("stageActionList");

		vo = service.insert(vo,flowStageList,stageActionList);

		if (vo.getId() == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "获取自增主键为空");
		}

		return ResponseUtil.getObject(vo,"插入成功");
	}




	/**
	 * 查看商机流程详情
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	public Object detail(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response)
			throws CrmMessageException {
		if (id == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "id不能为空");
		}
		Map<String, Object> returnMap = service.getDetail(id);
		return ResponseUtil.getObject(returnMap);
	}

	/**
	 * 修改商机动作
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.PUT)
	public Object update(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		JSONObject paramObject = RequestUtil.getParamObject(request);
		JSONObject flowData = paramObject.getJSONObject("flowData");//流程数据
		OppflowVO vo = RequestUtil.getVO(flowData, OppflowVO.class);

		vo.setId(id);

		String validMsg = validator(vo);
		if (!validMsg.equals("")){
        	throw new CrmMessageException(PCCodeConstant.ServerError, validMsg);
		}

		Map<String, List<Map<String, Object>>> ctrlInsertData = ctrlInsertData(paramObject);
		List<Map<String, Object>> flowStageList = ctrlInsertData.get("flowStageList");
		List<Map<String, Object>> stageActionList = ctrlInsertData.get("stageActionList");
		OppflowVO oppflowVO = service.update(vo, flowStageList, stageActionList);

		return ResponseUtil.getObject(oppflowVO,"修改成功");
	}


	private Map<String, List<Map<String, Object>>> ctrlInsertData(JSONObject paramObject) throws CrmMessageException {

		Map<String, List<Map<String, Object>>> returnMap = new HashMap<>();

		//2.维护 商机流程-商机阶段 的中间表 sprc_oppflow_stage（维护商机流程和商机阶段的顺序关系）
		List<Map<String, Object>> flowStageList = new ArrayList<>();
		//3.维护 商机流程-商机阶段-商机纬度-商机动作 的中间表 sprc_oppstage_action（维护商机流程上配置的全量信息表）
		List<Map<String, Object>> stageActionList = new ArrayList<>();
		JSONArray stageData = paramObject.getJSONArray("stageData");//阶段数组
		for(int i = 0; i < stageData.size(); i++) {
			Map<String, Object> flowStageMap = new HashMap<>();
			JSONObject stageJson =  stageData.getJSONObject(i);//阶段
			Long stage_id = stageJson.getLong("key");
			flowStageMap.put("oppstage_id", stage_id);//阶段
			Object winProbability = stageJson.get("winProbability");
			if(winProbability!= null) {
				String win_probability = stageJson.getString("winProbability");
				flowStageMap.put("win_probability", win_probability);
			}
			//flowStageMap.put("sort", i);//顺序 没有传
			flowStageList.add(flowStageMap);
			if (stageJson.get("children") == null) continue;
			JSONArray dimArray = stageJson.getJSONArray("children");//纬度数组
			for(int j = 0; j < dimArray.size(); j++){
				JSONObject dimJson = dimArray.getJSONObject(j);//纬度
				Long dim_id = dimJson.getLong("key");
				if (dimJson.get("children") == null) continue;
				JSONArray actionArray = dimJson.getJSONArray("children");//动作数组
				for(int k = 0; k < actionArray.size(); k++){
					JSONObject actionJson = actionArray.getJSONObject(k);//动作
					Long action_id = actionJson.getLong("key");
					Map<String, Object> stageActionMap = new HashMap<>();
					stageActionMap.put("oppstage_id", stage_id);
					stageActionMap.put("oppdim_id", dim_id);
					stageActionMap.put("oppaction_id", action_id);
					//stageActionMap.put("is_suggest", is_suggest);		//是否建议 1是2否 没有传
					stageActionList.add(stageActionMap);
				}
			}
		}
		returnMap.put("flowStageList",flowStageList);
		returnMap.put("stageActionList",stageActionList);
		return returnMap;
	}

	/**
	 * 批量删除
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "batch", method = RequestMethod.DELETE)
	public Object batchDelete(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		JSONObject paramObj = RequestUtil.getParamObject(request);
		String idStr = paramObj.getString("id");

		if (idStr == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "id参数为空");
		}
		@SuppressWarnings("unchecked")
		int result = service.delete(idStr);

		return ResponseUtil.getObject("删除成功");
	}

	/**
	 * 批量停启用
	 * @param request
	 * @param response
	 * @return
	 */

	@RequestMapping(value = "state", method = RequestMethod.PUT)
	public Object batchUpdateEnableState(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		JSONObject paramObj = RequestUtil.getParamObject(request);
		String idsStr = paramObj.getString("ids");

		if (idsStr == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "ids参数为空");
		}

		String[] idArray = idsStr.split(",");

		if (idArray.length == 0) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "至少选中一条记录");
		}

		Integer enableState = paramObj.getInt("enableState");

		if (enableState == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "停启用状态不能为空");
		}
		JSONObject data = new JSONObject();
		@SuppressWarnings("unchecked")
		List<OppflowVO> list = service.batchUpdateEnableState(idArray, enableState , (Map<String, Object>)paramObj.get("searchMap"));
		data.put("data",list);
		String msg="停用成功";
		if("1".equals(enableState.toString())){
			msg="启用成功";
		}
		return ResponseUtil.getObject(data,msg);
	}




	private String validator(OppflowVO vo) {

		if (vo == null) {
			return "转换实体失败";
		}

		if (StringUtils.isBlank(vo.getName())) {
        	return  "名称不能为空";
		}

		return "";
	}
	/**
	 * 获取分页信息
	 * @param paramObj
	 * @return Page<MeasuresVO>
	 */
	private Page<OppflowVO> getRequestPage(JSONObject paramObj) throws CrmMessageException {

		Integer page = paramObj.getInt(HttpKeyConstant.Page);
		Integer pageSize = paramObj.getInt(HttpKeyConstant.PageSize);

		if (page == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "page不能为空");
		}

		if (pageSize == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "pageSize不能为空");
		}

		return new Page<OppflowVO>(page, pageSize);
	}

	@RequestMapping(value = "biztype", method = RequestMethod.GET)
	public Object getBizType(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		Map<String, Object> resMap = service.getBizType();
		return ResponseUtil.getObject(resMap);
	}


}
